﻿Imports System.Drawing

Public Class AquariumFishList
    Inherits ItemListPage

    Protected Property PhotoNormalSize() As New Size() With {.width = 256, .height = 256}
    Protected Property PhotoThumbSize() As New Size() With {.width = 128, .height = 128}
    Protected Property AquariumID() As ULong
    Protected Property FishID() As ULong

    Protected Overrides ReadOnly Property DefaultOrder() As OrderCriterion
        Get
            Return New OrderCriterion("CommonName")
        End Get
    End Property

    Protected Overrides ReadOnly Property DefaultFilter() As FilterCriterion
        Get
            Return New FilterCriterion("ID", AquariumID)
        End Get
    End Property

    Protected Overrides ReadOnly Property CreatePageURL As String
        Get
            Return String.Format("~/Pages/AquariumFishList.aspx?AID={0}&Action=Add", AquariumID)
        End Get
    End Property

    Protected Overrides Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ULong.TryParse(Request.QueryString.Get("AID"), AquariumID)
        ULong.TryParse(Request.QueryString.Get("FID"), FishID)

        If Not IsPostBack Then
            If (AquariumID And Not FishID) AndAlso Request.QueryString.Get("Action") = "Add" Then
                If InsertionPermitted Then
                    UpdatePageTitle()
                    ListGrid.Visible = False
                    CreateButton.Visible = False
                    FishFormView.Visible = True
                    FishFormView.DefaultMode = FormViewMode.Insert
                    UpdateSpeciesList()
                Else
                    StopEditing()
                End If
            ElseIf (AquariumID AndAlso AquariumExists(AquariumID)) And (FishID AndAlso FishExists(FishID)) Then
                If Request.QueryString.Get("Action") = "Edit" Then
                    If ModificationPermitted Then
                        UpdatePageTitle()
                        ListGrid.Visible = False
                        CreateButton.Visible = False
                        FishFormView.Visible = True
                        FishFormView.DefaultMode = FormViewMode.Edit
                        UpdateDataSource()
                    Else
                        StopEditing()
                    End If
                End If
            ElseIf AquariumID AndAlso AquariumExists(AquariumID) Then
                MyBase.Page_Load(sender, e)
            Else
                RedirectToList()
            End If
        End If
    End Sub

    Protected Function AquariumExists(ByVal ID As ULong) As Boolean
        Dim gateway As New AquariumGateway()
        Return gateway.Exists(ID)
    End Function

    Protected Function FishExists(ByVal ID As ULong) As Boolean
        Dim gateway As New FishGateway()
        Return gateway.Exists(ID)
    End Function

    Protected Overrides Function CreateDataGateway() As DataGateway
        Return New AquariumFishGateway()
    End Function

    Protected Overrides Sub UpdateDataSource()
        If AquariumID = 0 Or FishID = 0 Then
            MyBase.UpdateDataSource()
        Else
            Dim gateway As New AquariumFishGateway()
            FishFormView.DataSource = gateway.FindByID(AquariumID, FishID)
            FishFormView.DataBind()
        End If
        UpdatePageTitle()
    End Sub

    Protected Sub UpdatePageTitle()
        Dim gateway As New AquariumGateway()
        TitleLabel.Text = gateway.FindByID(AquariumID).Rows.Item(0)("Title")
    End Sub

    Protected Sub UpdateSpeciesList()
        ' This is visible in Add/Edit views.
        ' Species are limitted only to the species not already existing in aquarium
        Dim speciesList As DropDownList = FishFormView.FindControl("SpeciesList")
        If speciesList IsNot Nothing Then
            Dim fishGateway As New FishGateway()
            Dim table As DataTable = fishGateway.FindNotInAquarium(AquariumID)
            speciesList.DataSource = table
            speciesList.DataBind()
            ' Show a message when all species exist in aquarium
            If table.Rows.Count = 0 Then
                Dim label As Label = FishFormView.FindControl("AllSpeciesLabel")
                label.Visible = True
            End If
        End If
    End Sub

    Protected Sub StartEditing()
        Dim redirectUrl As String = String.Format("~/Pages/AquariumFishList.aspx?AID={0}&FID={1}&Action=Edit", AquariumID, FishID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub StopEditing()
        Dim redirectUrl As String = String.Format("~/Pages/AquariumFishList.aspx?AID={0}", AquariumID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub RedirectToList()
        Response.Redirect("~/Pages/AquariumList.aspx")
    End Sub

    Protected Overridable ReadOnly Property ModificationPermitted() As Boolean
        Get
            Return Roles.IsUserInRole("Manager") Or UserHasOwnership()
        End Get
    End Property

    Protected ReadOnly Property UserHasOwnership() As Boolean
        Get
            Dim gateway As New AquariumGateway()
            Return gateway.HasOwnership(AquariumID, User.Identity.Name)
        End Get
    End Property

    Protected Sub SaveButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim gateway As New AquariumFishGateway()
            Dim totalFish As TextBox = FishFormView.FindControl("TotalFishTextBox")
            Dim photo As FileUpload = FishFormView.FindControl("PhotoFileUpload")
            Dim photoID As ULong
            If photo.HasFile() Then
                Dim fileName As String = PhotoUtils.GetUniqueFileName(photo.FileName)
                PhotoUtils.Save(fileName, photo.PostedFile.InputStream,
                                PhotoNormalSize, PhotoThumbSize)
                photoID = CreatePhoto(GetFish(FishID)("FullTitle"), fileName)
                gateway.Update(AquariumID, FishID, CInt(totalFish.Text), photoID)
            Else
                gateway.Update(AquariumID, FishID, CInt(totalFish.Text))
            End If

            StopEditing()
        End If
    End Sub

    Protected Sub CancelEditButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Protected Sub EditButton_Click(sender As Object, e As EventArgs)
        StartEditing()
    End Sub

    Protected Sub DeleteButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim gateway As New AquariumFishGateway()
            gateway.DeleteByID(AquariumID, FishID)
            StopEditing()
        End If
    End Sub

    Protected Sub CancelSubmitButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
        If InsertionPermitted Then
            Dim gateway As New AquariumFishGateway()
            Dim species As DropDownList = FishFormView.FindControl("SpeciesList")
            FishID = CULng(species.SelectedValue)
            Dim totalFish As TextBox = FishFormView.FindControl("TotalFishTextBox")
            Dim photo As FileUpload = FishFormView.FindControl("PhotoFileUpload")
            Dim photoID As ULong
            If photo.HasFile() Then
                Dim fileName As String = PhotoUtils.GetUniqueFileName(photo.FileName)
                PhotoUtils.Save(fileName, photo.PostedFile.InputStream,
                                PhotoNormalSize, PhotoThumbSize)
                photoID = CreatePhoto(GetFish(FishID)("FullTitle"), fileName)
                gateway.Insert(AquariumID, FishID, CInt(totalFish.Text), photoID)
            Else
                gateway.Insert(AquariumID, FishID, CInt(totalFish.Text))
            End If

            StopEditing()
        End If
    End Sub

    Private Function CreatePhoto(ByVal title As String, ByVal filename As String) As ULong
        Dim gateway As New PhotoGateway()
        Return gateway.Insert(title, "", GetCurrentUserID(), filename)
    End Function

    Private Function GetFish(ByVal fishID As ULong) As DataRow
        Dim gateway As New FishGateway()
        Return gateway.FindByID(fishID).Rows(0)
    End Function
End Class